package org.example.coursemangementserver.server.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.example.coursemangementserver.common.constant.ExceptionMessageConstant;
import org.example.coursemangementserver.common.exception.admin.AdminBaseException;
import org.example.coursemangementserver.common.exception.common.CommonException;
import org.example.coursemangementserver.common.exception.common.NoLoginException;
import org.example.coursemangementserver.common.exception.student.StudentBaseException;
import org.example.coursemangementserver.common.result.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理普通异常
     */
    @ExceptionHandler
    public Result exceptionHandler(CommonException ex){
        log.error("异常信息:{}",ex.getMessage());
        return Result.error(ex.getMessage());
    }


    /**
     * 处理文件操作异常
     */
    @ExceptionHandler
    public Result exceptionHandler(FileUploadException ex){
        log.error("文件操作异常信息:{}",ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理学生操作异常
     * @param ex
     * @return
     */
    @ExceptionHandler//此注解来标注处理特定异常的方法
    public Result exceptionHandler(StudentBaseException ex){
        log.error("账户操作异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理教务人员操作异常
     * @param ex
     * @return
     */
    @ExceptionHandler//此注解来标注处理特定异常的方法
    public Result exceptionHandler(AdminBaseException ex){
        log.error("管理员操作异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理未登录
     * @param noLoginException
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(NoLoginException noLoginException){
        log.error("未登录异常信息：{}",noLoginException.getMessage());
        return Result.error(ExceptionMessageConstant.NOT_LOGIN);
    }

    /**
     * 处理SQL操作异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error("SQL操作异常信息:{}",ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            return Result.error(ExceptionMessageConstant.REPEAT_USERNAME);
        }
        return Result.error(ex.getMessage());
    }

}
